<template>
  <div>
    <p>这里是首页</p>
    <el-divider>WebSocket练习</el-divider>
    <p>{{ websocketMsg }}</p>

  </div>
</template>

<script>
import websocketFeature from '@/util/websocket';
export default {
  data() {
    return {
      myWebsocketKey: '',
      websocketMsg: ''
    };
  },
  created() {
    this.initWebSocket();
  },
  methods: {
    /**
     * 初始化socket
     */
    initWebSocket() {
      let username = this.$store.getters['user/GET_INFO'].username;
      let socketUrl =
        'ws://' +
        window.global_value.VUE_APP_WEBSOCKET_URL +
        '/WebSocketServer/commonMessage/' +
        username +
        '@' +
        new Date().getTime();
      console.log('socketUrl', socketUrl);
      // 建立连接
      this.myWebsocketKey = websocketFeature.create(
        socketUrl,
        this.websocketMessageHandler.bind(this)
      );
    },
    /**
     * WebSocket返回信息
     */
    websocketMessageHandler(e) {
      this.websocketMsg = e.data;
    },
  },
  destroyed() {
    //销毁WebSocket
    if (this.myWebsocketKey && this.myWebsocketKey != '') {
      websocketFeature.remove(this.myWebsocketKey);
    }
  },
};
</script>

<style lang="scss" scoped></style>